//
//  ImageFileManager.swift
//  app路由
//
//  Created by zhaoguoteng on 2020/5/2.
//  Copyright © 2020 zhaoguoteng. All rights reserved.
//

import UIKit

class ImageFileManager {
    
    class func imageDirectory() -> URL? {
        
        guard let libraryDirectory = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).last else {
            return nil
        }
        
        let imageDirUrl = URL(fileURLWithPath: libraryDirectory).appendingPathComponent("image")
        
        var isDirectory = ObjCBool(true)
        if !FileManager.default.fileExists(atPath: imageDirUrl.absoluteString, isDirectory: &isDirectory) {
            do {
                try FileManager.default.createDirectory(atPath: imageDirUrl.path, withIntermediateDirectories: true, attributes: nil)
                return imageDirUrl
            } catch {
                fatalError(error.localizedDescription)
            }
        }
        
        return nil
    }
    
    // 保存图片
    class func saveImageToLocal(image: UIImage?) -> String? {
        
        guard let image = image else {
            return nil
        }
        
        guard let imageDirUrl = imageDirectory() else {
            return nil
        }
        
        if let imageData = image.jpegData(compressionQuality: 0.3) {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyyMMddhhmmssSSS"
            let imageName = "\(dateFormatter.string(from: Date())).jpg"
            let imageFileUrl = imageDirUrl.appendingPathComponent(imageName)
            do {
                try imageData.write(to: imageFileUrl)
            } catch {
                fatalError(error.localizedDescription)
            }
            return imageName
        }
        return nil
    }
    
    // 获取图片
    class func imageWithFileName(_ fileName: String?) -> UIImage? {
        guard let fileName = fileName else {
            return nil
        }
        
        guard let imageDirUrl = imageDirectory() else {
            return nil
        }
        
        let imageFileUrl = imageDirUrl.appendingPathComponent(fileName)
        
        guard FileManager.default.fileExists(atPath: imageFileUrl.path) else {
            return nil
        }
        
        do {
            let imageData = try Data(contentsOf: imageFileUrl)
            return UIImage(data: imageData)
        } catch {
            fatalError(error.localizedDescription)
        }
    }
    
    // 删除图片
    class func removeImageWithFileName(fileName: String?) {
        guard let fileName = fileName else {
            return
        }
        
        guard let imgDirUrl = imageDirectory() else {
            return
        }
        
        let filePath = imgDirUrl.appendingPathComponent(fileName)
        
        guard !FileManager.default.fileExists(atPath: filePath.path) else {
            return
        }
        
        do {
            try FileManager.default.removeItem(atPath: filePath.path)
        } catch {
            fatalError(error.localizedDescription)
        }
    }
    
    // 删除多余图片
    class func removeUnnecessaryImages() {
        SqliteManager.shareDBQ?.inDatabase({ db in
            
            var imgNames = [String]()
            
            do {
                let resSet = try db.executeQuery("SELECT img FROM routes", values: nil)
                while(resSet.next()) {
                    if let imgName = resSet.string(forColumn: "img") {
                        imgNames.append(imgName)
                    }
                }
                
                guard let imgDirUrl = imageDirectory() else {
                    return
                }
                
                let files = try FileManager.default.contentsOfDirectory(atPath: imgDirUrl.path)
                
                for p in files {
                    
                    if !imgNames.contains(p) {
                        let imgPath = imgDirUrl.appendingPathComponent(p)
                        try FileManager.default.removeItem(atPath: imgPath.path)
                    }
                }

            } catch {
                fatalError(error.localizedDescription)
            }
        })
    }
}
